/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.domain.Feedback;
import com.cms.entity.Category;
import com.cms.entity.Content;
import com.cms.entity.Model;
import com.cms.entity.ModelField;
import com.cms.service.CategoryService;
import com.cms.service.ModelFieldService;
import com.cms.service.ModelService;
import com.cms.utils.WebUtils;
import com.cms.utils.PinYinUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.*;


/**
 * Controller - 分类
 * 
 * 
 * 
 */
@Controller("adminCategoryController")
@RequestMapping("/admin/category")
public class CategoryController extends BaseController {

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ModelService modelService;

	@Autowired
	private ModelFieldService modelFieldService;
	
	/**
	 * 列表
	 */
	@RequestMapping
	public String index(ModelMap modelMap) {
		setListQuery();
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
		return getView("category/index");
	}

	/**
	 * 添加
	 */
	@RequestMapping("/add")
	public String add(ModelMap modelMap) {
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
		modelMap.addAttribute("models",modelService.findNormalList());
		return getView("category/add");
	}

	/**
	 * 检查目录
	 */
	@ResponseBody
	@RequestMapping("/check")
	public Map<String,Object> check(String cat,String code,Integer id){
		boolean checkCat = categoryService.checkCat(cat,id,getCurrentSite().getId());
		boolean checkCode = categoryService.checkCode(code,id,getCurrentSite().getId());
		Map<String,Object> data = new HashMap<>();
		data.put("checkCat", checkCat);
		data.put("checkCode", checkCode);
		return data;
	}
	
   /**
     * 内容模型模板
     */
   	@ResponseBody
   	@RequestMapping("/modelTemplate")
    public Map<String,Object> modelTemplate(Integer modelId){
        Model model = modelService.getById(modelId);
        Map<String,Object> data = new HashMap<>();
        data.put("listTemplate", model.getListTemplate());
        data.put("detailTemplate", model.getDetailTemplate());
        return data;
    }
    
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public String save(Category category,String[] chunkValues) {
		Integer modelId = category.getModelId();
		List<ModelField> modelFields = modelFieldService.findList(modelId);
		Map<String,Object> model = new HashMap<String,Object>();
		for(ModelField modelField : modelFields){
            model.put(modelField.getName(), WebUtils.getRequest().getParameter(modelField.getName()));
		}
		if(ArrayUtils.isNotEmpty(chunkValues)){
			category.setChunkValue(JSONArray.toJSONString(chunkValues));
		}else{
			category.setChunkValue(JSONArray.toJSONString(new String[]{}));
		}
		if(StringUtils.isBlank(category.getCat())){
			category.setCat(PinYinUtils.convertLower(category.getName()));
		}
		category.setSiteId(getCurrentSite().getId());
		category.setValue();
		category.setCreateDate(LocalDateTime.now());
		category.setUpdateDate(LocalDateTime.now());
		categoryService.save(category);
		return "redirect:"+getListQuery("/admin/category");
	}

	/**
	 * 编辑
	 */
	@RequestMapping("/edit")
	public String edit(Integer id,ModelMap modelMap) {
		Category category = categoryService.getById(id);
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
		modelMap.addAttribute("category", category);
		modelMap.addAttribute("models",modelService.findNormalList());
		if(category.getModelId() != null){
            List<ModelField> modelFields = modelFieldService.findList(category.getModelId());
			modelMap.addAttribute("modelFields", modelFields);
        }else{
			modelMap.addAttribute("modelFields", new ArrayList<ModelField>());
        }
		return getView("category/edit");
	}

	/**
	 * 更新
	 */
	@RequestMapping("/update")
	public String update(Category category,String[] chunkValues) {
		Integer modelId = category.getModelId();
		List<ModelField> modelFields = modelFieldService.findList(modelId);
		Map<String,Object> model = new HashMap<String,Object>();
		for(ModelField modelField : modelFields){
            model.put(modelField.getName(), WebUtils.getRequest().getParameter(modelField.getName()));
		}
		if(ArrayUtils.isNotEmpty(chunkValues)){
			category.setChunkValue(JSONArray.toJSONString(chunkValues));
		}else{
			category.setChunkValue(JSONArray.toJSONString(new String[]{}));
		}
		if(StringUtils.isBlank(category.getCat())){
			category.setCat(PinYinUtils.convertLower(category.getName()));
		}
		category.setValue();
		category.setUpdateDate(LocalDateTime.now());
		categoryService.updateById(category);
		return "redirect:"+getListQuery("/admin/category");
	}
	
	/**
	 * 修改状态
	 */
	@ResponseBody
	@RequestMapping("/updateStatus")
	public Feedback updateStatus(Boolean value,Integer id){
		Integer status = BooleanUtils.toInteger(value);
		Category category = categoryService.getById(id);
		category.setStatus(status);
		category.setUpdateDate(LocalDateTime.now());
		categoryService.updateById(category);
		return Feedback.success(new HashMap<>());
	}
	
   /**
     * 修改排序
     */
   	@ResponseBody
   	@RequestMapping("/updateSort")
    public Feedback updateSort(String sortArray){
        JSONArray jsonArray = JSONArray.parseArray(sortArray);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
            Integer sort = jsonObject.getInteger("sort");
            Category category = categoryService.getById(id);
            category.setSort(sort);
			categoryService.updateById(category);
        }
        return Feedback.success(new HashMap<>());
    }

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Feedback delete(Integer id) {
		Category category = categoryService.getById(id);
		if (category == null) {
			return Feedback.error("分类不存在");
		}
		List<Category> children = category.getChildren();
		if (children != null && !children.isEmpty()) {
			return Feedback.error("存在下级分类，无法删除");
		}
		List<Content> contents = category.getContents();
		if (contents != null && !contents.isEmpty()) {
			return Feedback.error("存在下级内容，无法删除");
		}
		categoryService.removeById(id);
		return Feedback.success(new HashMap<>());
	}

}